package com.heima.comment.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private GreenScan greenScan;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        //   条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                        .limit(dto.getSize())
                , ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //   3.1 如果未登录直接 返回评论回复列表
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        //   3.2 如果登录，需要判断哪些回复点过赞
        //   思路:
        List<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            try {
                //        遍历 当前回复列表，将每一个回复信息 封装成 vo
                BeanUtils.copyProperties(apCommentRepayVO, apCommentRepay);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            //        基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
            //  判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            if (apCommentRepayLike != null) {
                apCommentRepayVO.setOperation((short) 0);
            }
            apCommentRepayVOS.add(apCommentRepayVO);
        }
        return ResponseResult.okResult(apCommentRepayVOS);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        ApUser user = AppThreadLocalUtils.getUser();
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //   回复内容安全校验
        //  简单: 不校验  普通: 阿里云内容检查，有问题抛异常  困难：阿里云内容检查，有问题替换为**
        String content = dto.getContent();
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            //        过滤掉违规词汇：替换为**
            if (!scanResult.getSuggestion().equals("pass")) {
                content = scanResult.getFilteredContent();
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "阿里云文本审核失败");
        }
        //敏感词校验，如存在替换为**
        //获取敏感词
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        List<String> sensitives = sensitivesResult.getData();
        //替换敏感词
        for (String sensitive : sensitives) {
            content = content.replace(sensitive, "**");
        }
        //2. 根据评论id查询评论信息  检查是否存在
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在");
        }
        //3. 保存评论回复信息
        //远程查询当前登陆用户信息
        ResponseResult<ApUser> apUserResponse = userFeign.findUserById(user.getId());
        ApUser apUser = apUserResponse.getData();

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(content);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        mongoTemplate.insert(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        apComment.setReply(apComment.getReply() + 1);
        apComment.setUpdatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        //   校验是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //   校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentRepayId())), ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论回复信息不存在");
        }
        //1. 如果是点赞  判断是否点过赞
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId())), ApCommentRepayLike.class);
        //      点过赞提示请勿重复点赞
        if (dto.getOperation() == 0) {
            if (apCommentRepayLike != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "已经点过赞，请勿重复点赞");
            }
            //   未点过赞   保存点赞信息到mongo
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            //      未点过赞， 保存点赞信息
            mongoTemplate.insert(apCommentRepayLike);
            //   并修改评论信息的点赞数量( + 1)
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
        } else {
            // 如果是取消赞
            //      删除点赞信息
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(dto.getCommentRepayId()).and("authorId").is(user.getId())), ApCommentRepayLike.class);
            //  并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
            if (apCommentRepay.getLikes() <= 0) {
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "点赞数量出错");
            }
            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
        }
        //  并将回复信息的点赞数量字段
        // 返回当前回复的最新点赞数量      数据的key:  likes
        Map<String, Integer> map = new HashedMap();
        map.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
